package com.matezk.sael;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.matezk.sael.beans.Action;
import com.matezk.sael.hardware.GpioControl;
import com.matezk.sael.tencent.TencentService;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private ButtonClickCallBack buttonClickCallBack = new ButtonClickCallBack();
    private GpioControl gpioControl = GpioControl.getInstance();

    private Handler handler = new Handler();

    private TextView dateView;
    private TextView timeView;

    private Button powerButton;
    private Button powerSwitchButton;
    private Button systemButton;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "MainActivity onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        context = this;

        // 隐藏导航栏
        Intent intent = new Intent("gzpeite.intent.systemui.hidenavigation");
        sendBroadcast(intent);

        // 隐藏状态栏
        intent = new Intent("gzpeite.intent.systemui.hidestatusbar");
        sendBroadcast(intent);

        // 获取界面组件
        powerButton = findViewById(R.id.btn_power);
        powerButton.setText(GpioControl.PowerState.ON == gpioControl.getPowerState() ? "合闸" : "分闸");
        powerButton.setOnClickListener(buttonClickCallBack);
        powerSwitchButton = findViewById(R.id.btn_power_switch);
        powerSwitchButton.setText(GpioControl.PowerType.AQD == gpioControl.getPowerType() ? "安全电" : "市电");
        powerSwitchButton.setOnClickListener(buttonClickCallBack);
        systemButton = findViewById(R.id.btn_system);
        systemButton.setOnClickListener(buttonClickCallBack);
        dateView = findViewById(R.id.date_view);
        timeView = findViewById(R.id.time_view);
        String items[] = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()).split(" ");
        dateView.setText(items[0]);
        timeView.setText(items[1]);

        // 注册广播接收器
        ActivityBroadcastReceiver receiver = new ActivityBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Action.Update_Power_Switch);
        registerReceiver(receiver, filter);
        filter = new IntentFilter();
        filter.addAction(Action.Update_Power_Type);
        registerReceiver(receiver, filter);

        // 时间变化
        handler.postDelayed(new UpdateTimeRunnable(), 1000);

        // 启动MQTT后台服务
        startService(new Intent(getBaseContext(), TencentService.class));
    }

    // 按钮点击事件
    private class ButtonClickCallBack implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Button target = (Button) v;
            switch (v.getId()) {
                case R.id.btn_power_switch:
                    gpioControl.togglePowerType(powerType -> {
                        Intent intent = new Intent();
                        intent.setAction(Action.Report_Power_Type);
                        intent.putExtra("type", powerType);
                        sendBroadcast(intent);
                        if (powerType == GpioControl.PowerType.AQD) {
                            target.setText("安全电");
                            target.setLetterSpacing(0);
                        } else {
                            target.setText("市电");
                            target.setLetterSpacing(0.7f);
                        }

                        // 弹出密码输入框
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.layout_password, findViewById(R.id.password_dialog));
                        // 密码输入框组件
                        View.OnClickListener keyCallback = view -> {
                            TextView pin = layout.findViewById(R.id.view_input);
                            switch (view.getId()) {
                                case R.id.key_1:
                                    pin.setText(pin.getText() + "1");
                                    break;
                                case R.id.key_2:
                                    pin.setText(pin.getText() + "2");
                                    break;
                                case R.id.key_3:
                                    pin.setText(pin.getText() + "3");
                                    break;
                                case R.id.key_4:
                                    pin.setText(pin.getText() + "4");
                                    break;
                                case R.id.key_5:
                                    pin.setText(pin.getText() + "5");
                                    break;
                                case R.id.key_6:
                                    pin.setText(pin.getText() + "6");
                                    break;
                                case R.id.key_7:
                                    pin.setText(pin.getText() + "7");
                                    break;
                                case R.id.key_8:
                                    pin.setText(pin.getText() + "8");
                                    break;
                                case R.id.key_9:
                                    pin.setText(pin.getText() + "9");
                                    break;
                                case R.id.key_0:
                                    pin.setText(pin.getText() + "0");
                                    break;
                                case R.id.key_del:
                                    CharSequence text = pin.getText();
                                    if (text.length() > 0) {
                                        pin.setText(text.subSequence(0, text.length() - 1));
                                    }
                                    break;
                            }
                        };

                        Button key1 = layout.findViewById(R.id.key_1);
                        key1.setOnClickListener(keyCallback);
                        Button key2 = layout.findViewById(R.id.key_2);
                        key2.setOnClickListener(keyCallback);
                        Button key3 = layout.findViewById(R.id.key_3);
                        key3.setOnClickListener(keyCallback);
                        Button key4 = layout.findViewById(R.id.key_4);
                        key4.setOnClickListener(keyCallback);
                        Button key5 = layout.findViewById(R.id.key_5);
                        key5.setOnClickListener(keyCallback);
                        Button key6 = layout.findViewById(R.id.key_6);
                        key6.setOnClickListener(keyCallback);
                        Button key7 = layout.findViewById(R.id.key_7);
                        key7.setOnClickListener(keyCallback);
                        Button key8 = layout.findViewById(R.id.key_8);
                        key8.setOnClickListener(keyCallback);
                        Button key9 = layout.findViewById(R.id.key_9);
                        key9.setOnClickListener(keyCallback);
                        Button key0 = layout.findViewById(R.id.key_0);
                        key0.setOnClickListener(keyCallback);
                        Button keyDel = layout.findViewById(R.id.key_del);
                        keyDel.setOnClickListener(keyCallback);
                        Button keyEnter = layout.findViewById(R.id.key_enter);
                        keyEnter.setOnClickListener(keyCallback);

                        new AlertDialog.Builder(context).setView(layout).show();
                    });
                    break;
                case R.id.btn_power:
                    gpioControl.togglePowerState(powerState -> {
                        Intent intent = new Intent();
                        intent.setAction(Action.Report_Power_Switch);
                        intent.putExtra("state", powerState);
                        sendBroadcast(intent);
                        target.setText(powerState == GpioControl.PowerState.ON ? "合闸" : "分闸");
                    });
                    break;
                case R.id.btn_system:
                    Intent intent = new Intent(MainActivity.this, SystemActivity.class);
                    startActivity(intent);
                default:
                    break;
            }
        }
    }

    private class UpdateTimeRunnable implements Runnable {
        @Override
        public void run() {
            String items[] = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()).split(" ");
            dateView.setText(items[0]);
            timeView.setText(items[1]);
            handler.postDelayed(this, 1000);
        }
    }

    private class ActivityBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (Action.Update_Power_Type.equals(intent.getAction())) {
                    GpioControl.PowerType type = (GpioControl.PowerType)intent.getSerializableExtra("type");
                    powerSwitchButton.setText(type == GpioControl.PowerType.AQD ? "安全电" : "市电");
                } else if (Action.Update_Power_Switch.equals(intent.getAction())) {
                    GpioControl.PowerState state = (GpioControl.PowerState)intent.getSerializableExtra("state");
                    powerButton.setText(state == GpioControl.PowerState.ON ? "合闸" : "分闸");
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "MainActivity onDestroy");
        super.onDestroy();
        stopService(new Intent(getBaseContext(), TencentService.class));
    }
}